﻿using Microsoft.Data.SqlClient;
using netcore_comm.SqlSugar;
using netcore_service.IRepository;
using netcore_service.IService;
using netcore_service.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace netcore_service.Service
{
    public class ChatService : IChatService
    {
        private readonly IChatRepository _context;
        private readonly IMessageRepository _messageRepository;
        private readonly ISqlSugarFactory _sqlSugarFactory;

        public ChatService(IChatRepository context, ISqlSugarFactory sqlSugarFactory, IMessageRepository messageRepository)
        {
            _context = context;
            _sqlSugarFactory = sqlSugarFactory;
            _messageRepository = messageRepository;
        }

        public async Task<ChatSession> CreateSessionAsync(string customerId, string customerName,string school, string schoolName, string logo, string? initialMessage = null)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            // 验证用户存在且是客户
            var customer = await _context.GetModelAsync(db, e=>e.CustomerId==customerId&&e.School==school);
            if (customer!=null)
            {
                return customer;
            }
            //if (customer == null)
            //    throw new ArgumentException("Invalid customer");

            var session = new ChatSession
            {
                CustomerId = customerId,
                CustomerName= customerName,
                Status = SessionStatus.Waiting,
                CreatedAt = DateTime.UtcNow,
                School=school,
                SchoolName=schoolName,
                Logo=logo
            };

            await _context.InsertAsync(db, session);

            // 如果有初始消息，保存它
            if (!string.IsNullOrEmpty(initialMessage))
            {
                await SendMessageAsync(session.Id, customerId, customerName,logo, initialMessage);
            }

            return session;
        }

        public async Task<ChatSession?> AcceptSessionAsync(string sessionId, string agentId,string agentName,string school)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);

            var session = await _context
                .GetModelAsync(db, s => s.Id == sessionId);

            if (session == null)
                return null;

            if (session.Status!=SessionStatus.Waiting)
            {
                return session;
            }
            // 验证客服存在
            //var agent = await _context.Users.FindAsync(agentId);
            //if (agent == null || agent.Role != UserRole.Agent)
            //    throw new ArgumentException("Invalid agent");

            session.AgentId = agentId;
            session.Status = SessionStatus.Active;
            session.LastMessageTime = DateTime.UtcNow;
            session.AgentName = agentName;

            await _context.UpdateAsync(db, session);
            return session;
        }

        public async Task<Message> SendMessageAsync(string sessionId, string senderId, string senderName,string Logo, string content, MessageType messageType = MessageType.Text)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);

            var session = await _context.GetModelAsync(db, sessionId);
            if (session == null) throw new ArgumentException("Session not found");

            //var sender = await _context.Users.FindAsync(senderId);
            //if (sender == null) throw new ArgumentException("Sender not found");

            var message = new Message
            {
                SessionId = sessionId,
                SenderId = senderId,
                SenderName = senderName,
                Content = content,
                MessageType = messageType,
                SentAt = DateTime.UtcNow,
                Logo=Logo
            };

            await _messageRepository.InsertAsync(db, message);

            //更新会话信息
            session.MessageCount++;
            session.LastMessageTime = DateTime.UtcNow;

            await _context.UpdateAsync(db, session);
            return message;
        }

        public async Task<List<ChatSession>> GetWaitingSessionsAsync(string school)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            return await _context.GetListAsync(db, s => s.Status == SessionStatus.Waiting, s => s.CreatedAt);
        }

        public async Task<List<ChatSession>> GetUserSessionsAsync(string userId)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);

            return await _context.GetListAsync(db, s => s.CustomerId == userId || s.AgentId == userId, s => s.LastMessageTime ?? s.CreatedAt, SqlSugar.OrderByType.Desc);
        }

        public async Task<List<Message>> GetSessionMessagesAsync(string sessionId, int count)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            var list = await _messageRepository.GetListAsync(db, m => m.SessionId == sessionId, m => m.SentAt,SqlSugar.OrderByType.Desc);
            return list.Take(count).ToList();
        }

        public async Task<bool> CloseSessionAsync(string sessionId)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);

            var session = await _context.GetModelAsync(db, sessionId);
            if (session == null) return false;

            session.Status = SessionStatus.Closed;
            session.EndedAt = DateTime.UtcNow;

            await _context.UpdateAsync(db, session);
            return true;
        }

        public async Task MarkMessagesAsReadAsync(string sessionId, string userId)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);

            var messages = await _messageRepository.GetListAsync(db, m => m.SessionId == sessionId && m.SenderId != userId && !m.IsRead);

            foreach (var message in messages)
            {
                message.IsRead = true;
                await _messageRepository.UpdateAsync(db, message);
            }

        }

        public async Task<ChatSession> GetUserSessionsByCustomer(string userId)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            return await _context.GetModelAsync(db, s => s.CustomerId == userId, s => s.LastMessageTime ?? s.CreatedAt, SqlSugar.OrderByType.Desc);
        }

        public async Task<List<ChatSession>> GetScoolSessionsAsync(string School)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);

            return await _context.GetListAsync(db, s => s.School== School, s => s.LastMessageTime ?? s.CreatedAt, SqlSugar.OrderByType.Desc);
        }

        public async Task<List<ChatSession>> SchoolSessionsByCustomer(string userId)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            return await _context.GetListAsync(db, s => s.CustomerId == userId, s => s.LastMessageTime ?? s.CreatedAt, SqlSugar.OrderByType.Desc);
        }
    }
}
